package org.atlantis.grosbeak.lang;

/**
 * 一个简单的键-值对。
 * 
 * @author <a href="mailto:seenoevil.cn@gmail.com">SeeNoEvil</a>
 * 
 * @param <T>
 */
public class Pair<T> {

	private static final String FMT_A = "%s=%s";
	private static final String FMT_B = "%s='%s'";
	private static final String FMT_C = "%s=\"%s\"";

	private String key;
	private T value;
	private String format;

	public Pair() {
	};

	public Pair(String key, T value) {
		this.key = key;
		this.value = value;
		format = FMT_C;
	}

	public String getKey() {
		return key;
	}

	public void setKey(String key) {
		this.key = key;
	}

	public T getValue() {
		return value;
	}

	public void setValue(T value) {
		this.value = value;
	}

	public static Pair<String> create(String str) {
		String[] ss = Strings.spliteIgnoreBlank(str, "=");
		String key = null;
		String value = null;
		String pattern = FMT_C;
		if (null != ss) {
			if (ss.length == 1) {
				key = ss[0];
			} else if (ss.length == 2) {
				key = ss[0];
				if (ss[1].length() > 0) {
					if (ss[1].charAt(0) == '"') {
						value = ss[1].substring(1, ss[1].length() - 2);
						pattern = FMT_C;
					} else if (ss[1].charAt(0) == '\'') {
						value = ss[1].substring(1, ss[1].length() - 2);
						pattern = FMT_B;
					} else {
						value = ss[1];
						pattern = FMT_A;
					}
				}
			}
		}
		Pair<String> re = new Pair<String>(key, value);
		re.format = pattern;
		return re;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj instanceof Pair<?>)
			if (Strings.equals(((Pair<?>) obj).key, key)
					&& ((Pair<?>) obj).value.equals(value))
				return true;
		return false;
	}

	@Override
	public int hashCode() {
		return value.hashCode();
	}

	@Override
	public String toString() {
		String valueStr = (null == value) ? "" : value.toString();
		valueStr.replace("\"", "&quot;");
		return String.format(format, key, valueStr);
	}
}
